#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include <string.h>
#include <ctype.h>


int main(){


    // 监听文件描述符
    int lfd = socket(AF_INET,SOCK_STREAM,0);
    if (lfd < 0){
        fprintf(stderr,"socket error!\n");
        exit(-1);
    }

    // 绑定IP地址和端口号
    struct sockaddr_in saddr;
    // 初始化
    bzero(&saddr,sizeof(saddr));
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(8888);
    saddr.sin_addr.s_addr = htonl(INADDR_ANY);
    bind(lfd,(struct sockaddr *)&saddr,sizeof(saddr));

    // 监听
    listen(lfd,128);

    // 通信文件描述符
    struct sockaddr_in caddr;
    socklen_t caddr_len = sizeof(caddr);
    bzero(&caddr,sizeof(caddr));
    int cfd = accept(lfd,(struct sockaddr *)&caddr,&caddr_len);
    printf("client: ip is [%s], port is [%d]\n",inet_ntoa(caddr.sin_addr),ntohs(caddr.sin_port));

    // 读取数据
    char buf[1024];
    int n;
    memset(buf,'\0',sizeof(buf));
    while ((n = read(cfd,buf,sizeof(buf))) > 0){
        printf("data:%s\n",buf);
        for (size_t i = 0; i < n; i++){
            buf[i] = toupper(buf[i]);
        }
        // 写
        write(cfd,buf,n);
    }
    
    if (n < 0){
        fprintf(stderr,"read error!\n");
        exit(-1);
    }

    // 关闭
    close(cfd);
    close(lfd);
    
    return 0;
}